<?php
declare (strict_types = 1);

namespace app\controller\api\v1\site;

use app\controller\api\ApiController;
use app\exception\AuthException;
use app\exception\LogicException;
use app\service\logic\api\site\SiteService;
use app\service\logic\common\tool\UploadService;
use app\validate\common\site\SiteValidate;
use think\App;
use think\Request;
use think\response\Json;

class SiteController extends ApiController
{
    protected $service;

    public function __construct(App $app, SiteService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    /**
     * 登录
     *
     * @return Json
     * @throws AuthException
     * @throws LogicException
     */
    public function login(): Json
    {
        $result = $this->_universalLogin();
        $token = $result['token'];
        return amis([
            'token' => $token,
            'user' => $result['user'],
            'type' => $result['type'],
        ]);
    }

    /**
     * 通用登录
     *
     * @return array
     * @throws LogicException
     * @throws AuthException
     */
    private function _universalLogin()
    {
        $params = $this->request->param(['mobile', 'captcha', 'type', 'from']);
        $this->validate($params, SiteValidate::class . '.login');
        $type = $params['type'] ?? '1';
        if ('1' == $type) {
            // 用户登录
            $result = $this->service->userLogin($params);
            event('AfterUserLogin', ['id' => $result['user']['id'],  'token' => $result['token']]); // 可队列
        } else {
            // 专家登录
            $result = $this->service->expertLogin($params);
            event('AfterExpertLogin', ['id' => $result['user']['id'],  'token' => $result['token']]); // 可队列
        }
        $result['type'] = $type;
        $this->service->removeCaptcha($params);
        return $result;
    }

    /**
     * 非安全上传接口(不建议使用-!-)
     *
     * @return Json
     */
    public function upload()
    {
        $params = request()->only(['type']);
        $file = request()->file() ?? [];
        $this->validate($file, SiteValidate::class . '.file');
        $this->validate($params, SiteValidate::class . '.upload');

        $result = invoke(UploadService::class)->upload($params, $file);
        return amis([
            'value' => $result
        ]);
    }

    /**
     * 发送验证码
     *
     * @param Request $request
     * @return Json
     */
    public function captcha(Request $request)
    {
        $params = $request->only(['mobile']);
        $this->validate($params, SiteValidate::class . '.send');

        // 获取忽略验证码手机号
        $whiteList = explode(',', config('logic.mobile_white_list'));
        if (in_array($params['mobile'], $whiteList)) {
            $result = '该手机号码已在验证码白名单中,输入1即可';
        } else {
            $result = invoke(\app\service\logic\common\site\SiteService::class)->send($params);
        }

        return amis([
            'sms_code' => $result
        ]);
    }
}
